package com.cavy.platform.client.message;

import com.cavy.platform.client.domain.ContainerRunningException;
import com.cavy.platform.client.domain.Job;
import com.cavy.platform.client.domain.RunningParameter;
import com.cavy.platform.client.service.AbstractMessageHandlerImpl;
import com.cavy.platform.client.service.AgentClose;
import com.cavy.platform.client.service.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 唐旭
 * @Date 2018/7/24
 * 任务分发后处理
 */
@Service
@Slf4j
public class JobDispatcher extends AbstractMessageHandlerImpl<JobDispatchMessage> implements MessageHandler, AgentClose {
    private List<Job> jobList = new ArrayList<>();

    @Override
    protected Class<JobDispatchMessage> getTypeClass() {
        return JobDispatchMessage.class;
    }

    @Override
    protected void hand(JobDispatchMessage message) {
        Job job = message.getJob();
        jobList.add(job);
        job.run(new RunningParameter(), 0);
        log.info("正在执行job:{},{},{},{}", job.getWorkspaceName(), job.getProjectName(), job.getPipelineName(), job.getNumber());
    }

    public int currentJobCount() {
        return jobList.size();
    }


    public void removeJob(String number, String pipelineName, String projectName, String workspaceName) {
        Iterator<Job> iterator = jobList.iterator();
        while (iterator.hasNext()) {
            Job job = iterator.next();
            if (job.getNumber().equals(number) && job.getPipelineName().equals(pipelineName)
                    && job.getProjectName().equals(projectName) && job.getWorkspaceName().equals(workspaceName)) {
                iterator.remove();
                break;
            }
        }
    }

    @Override
    public void close() {
        for (Job job : jobList) {
            try {
                job.stop();
            } catch (InterruptedException | ContainerRunningException e) {
                log.error(e.getMessage());
            }
        }
    }
}
